<!DOCTYPE html>
<html>
<head>
	<meta name="viewport" content="width=device-width,minimum-scale=1.0,initial-scale=1,user-scalable=yes"/>
	<style>
	body {
		font-family: 'Segoe UI Light', 'Segoe UI', 'Roboto', sans-serif;
		box-sizing: border-box;
		margin: 16px;
	}
	img {
		width: 400px;
	}
	pre {
		white-space: pre-line;
	}
	.layout {
		display: flex;
	}
	.box + .box {
		margin-left: 16px;
	}
	</style>
</head>
<body>

	<input id="fileinput" type="file">

	<div class="layout">

		<div class="box">
			<h3>Original image</h3>
			<img id="original">
			<pre id="original-desc"></pre>
		</div>

		<div class="box">
			<h3>Extracted thumbnail</h3>
			<img id="thumbnail">
			<pre id="thumbnail-desc"></pre>
		</div>

	</div>

	<!-- UMD module that exports itself to window.exifr -->
	<script src="../dist/lite.umd.js"></script>

	<script>

		function promiseImg(img) {
			if (img.naturalWidth !== 0) {
				return Promise.resolve()
			} else {
				return new Promise((resolve, reject) => {
					img.onload = resolve
					img.onerror = reject
				})
			}
		}

		var promiseTimeout = millis => new Promise(resolve => setTimeout(resolve, millis))

		let original = document.querySelector("#original")
		let thumbnail = document.querySelector("#thumbnail")
		let originalDesc = document.querySelector("#original-desc")
		let thumbnailDesc = document.querySelector("#thumbnail-desc")

		processFile('../test/fixtures/IMG_20180725_163423.jpg')

		async function processFile(arg) {
			let url
			if (arg instanceof Blob)
				url = URL.createObjectURL(arg)
			else
				url = arg
			original.src = url
			await promiseImg(original)
			// original image loaded, extract thumb
			let t0 = performance.now()
			thumbnail.src = await exifr.thumbnailUrl(original)
			console.log('original ', original.src)
			console.log('thumbnail', thumbnail.src)
			let t1 = performance.now()
			// thumb extracted
			printImgInfo(original, originalDesc)
			try {
				await promiseTimeout() // needed for reloading after selecting another img
				await promiseImg(thumbnail)
				printImgInfo(thumbnail, thumbnailDesc, `extracted in ${Math.round(t1 - t0)} ms`)
			} catch (err) {
				printImgInfo(thumbnail, thumbnailDesc, `The file has no thumbnail`)
			}
		}

		function printImgInfo(img, pre, ...lines) {
			if (img.naturalWidth > 0 && img.naturalHeight > 0) {
				pre.innerHTML = [
					`width: ${img.naturalWidth}`,
					`height: ${img.naturalHeight}`,
					...lines
				].join('\n')
			} else {
				pre.innerHTML = lines.join('\n')
			}
		}

		document.querySelector('input[type="file"]').addEventListener('change', async e => {
			processFile(e.target.files[0])
		})

	</script>

</body>
</html>